﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;

namespace SkiTracker.Converter
{
    /// <summary>
    /// Generic Converter for nullable booleans to any type. 
    /// </summary>
    /// <remarks>For explanation see subclass <see cref="BooleanToVisibilityConverter"/>.</remarks>
    public class GenericNullableBooleanConverter<T> : GenericBooleanConverter<T>
    {
        public GenericNullableBooleanConverter(T trueValue, T falseValue, T nullValue) : base ( trueValue, falseValue)
        {
            Null = nullValue;
        }

        /// <summary>
        /// Gets or sets the value that represents <see cref="Null"/>.
        /// </summary>
        public T Null { get; set; }

        #region IValueConverter Members

        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {

            if ((value == null || value is bool) && targetType == typeof (T))
            {
                var x = value as bool?;
                if (!x.HasValue) return Null;
                return (x.Value) ? True: False;
            }
            return DependencyProperty.UnsetValue;
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {

            if (Null.Equals(null) && value == null) return null;
            if (True.Equals(null) && value == null) return null;
            if (False.Equals(null) && value == null) return null;
            
            if (value is T && targetType == typeof (bool?))
            {
                if (EqualityComparer<T>.Default.Equals((T)value, True)) return true;
                if (EqualityComparer<T>.Default.Equals((T)value, False)) return false;
                if (EqualityComparer<T>.Default.Equals((T)value, Null)) return null;
                return DependencyProperty.UnsetValue;
            }
            return DependencyProperty.UnsetValue;
        }

        #endregion
    }
}